package edu.gatech.oad.antlab.m7final;

import javax.imageio.ImageIO;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;


public class StorePanel extends JPanel{
	Image newImg;
	BufferedImage image;
	private JTextField txtAmmo;
	private JTextField txtFood;
	private JTextField txtTongue;
	private JTextField txtClothing;
	private JTextField txtOxen;
	private JTextField txtWheel;
	private JTextField txtAxle;
	
	private JTextField[] quantityArray;
	private JLabel[] storeLabelsArray;
	private JLabel[] wagonLabelsArray;
	
	private JLabel lblCurrentCost;
	private JLabel lblMoneyLeft;
	
	private ButtonListener listener;
	
	private int total;
	private int totalWeight;
	private JLabel label_1, label_2, label_3, storeOxenAmount, storeFoodAmount,
	storeClothingAmount, storeAmmoAmount, storeWheelAmount, storeAxleAmount, storeTongueAmount;
	
	
	private ArrayList<Item> itemList; 
	private ArrayList<Item> items;
	private StoreInventory storeInventory;
	private WagonInventory wagonInventory;
	private StoreController storeController;
	
	private JButton btnBuy;
	private JButton btnSell;
	private JButton btnReturn;
	
	private JLabel lblWeightAdded ;
	private JLabel lblWagonWeight;
	
	public StorePanel(StoreInventory storeInventory, WagonInventory wagonInventory, StoreController controller) {
		
		
		listener = new ButtonListener();
		
		this.storeInventory = storeInventory;
		this.wagonInventory = wagonInventory;
		this.storeController = controller;
		
		items = new ArrayList<Item>();
		
		ImageIcon icon = new ImageIcon("C:\\Users\\Akbar\\Desktop\\storebgfinal.jpg");
		Image img = icon.getImage();
		newImg = img.getScaledInstance(601, 497,  java.awt.Image.SCALE_SMOOTH);
		setLayout(null);
		
		// GUI code starts here
		JLabel lblQuantity = new JLabel("#");
		lblQuantity.setBounds(215, 163, 15, 14);
		add(lblQuantity);
		
		JLabel lblAmount = new JLabel("Amount");
		lblAmount.setBounds(501, 163, 65, 14);
		lblAmount.setHorizontalAlignment(SwingConstants.CENTER);
		add(lblAmount);
		
		JLabel lblPrice = new JLabel("Price");
		lblPrice.setBounds(74, 163, 37, 14);
		add(lblPrice);
		
		JLabel lblWeight = new JLabel("Weight");
		lblWeight.setBounds(138, 163, 48, 14);
		add(lblWeight);
		
		JLabel lblPrice_1 = new JLabel("Price");
		lblPrice_1.setBounds(375, 163, 37, 14);
		add(lblPrice_1);
		
		JLabel lblWeight_1 = new JLabel("Weight");
		lblWeight_1.setBounds(676, 76, 34, 14);
		add(lblWeight_1);
		
		JLabel label = new JLabel("#");
		label.setBounds(721, 76, 8, 14);
		add(label);
		
		JLabel lblWagonInventory = new JLabel("Wagon Inventory");
		lblWagonInventory.setBounds(409, 142, 108, 17);
		lblWagonInventory.setFont(new Font("Times New Roman", Font.BOLD, 14));
		add(lblWagonInventory);
		
		JLabel lblStoreInventory = new JLabel("Store Inventory");
		lblStoreInventory.setBounds(78, 142, 108, 17);
		lblStoreInventory.setFont(new Font("Times New Roman", Font.BOLD, 14));
		add(lblStoreInventory);
		
		txtFood = new JTextField();
		txtFood.setText("0");
		txtFood.setBounds(258, 199, 75, 20);
		add(txtFood);
		txtFood.setColumns(10);
		
		txtClothing = new JTextField();
		txtClothing.setText("0");
		txtClothing.setBounds(258, 227, 75, 20);
		add(txtClothing);
		txtClothing.setColumns(10);
		
		txtAxle = new JTextField();
		txtAxle.setText("0");
		txtAxle.setBounds(258, 311, 75, 20);
		add(txtAxle);
		txtAxle.setColumns(10);
		
		txtTongue = new JTextField();
		txtTongue.setText("0");
		txtTongue.setBounds(258, 339, 75, 20);
		add(txtTongue);
		txtTongue.setColumns(10);
		
		txtWheel = new JTextField();
		txtWheel.setText("0");
		txtWheel.setBounds(258, 283, 75, 20);
		add(txtWheel);
		txtWheel.setColumns(10);
		
		txtAmmo = new JTextField();
		txtAmmo.setText("0");
		txtAmmo.setBounds(258, 255, 75, 20);
		add(txtAmmo);
		txtAmmo.setColumns(10);
		
		txtOxen = new JTextField();
		txtOxen.setText("0");
		txtOxen.setBounds(258, 171, 75, 20);
		add(txtOxen);
		txtOxen.setColumns(10);
		
		//oxen label
		JLabel lblOxen = new JLabel("Oxen");
		lblOxen.setBounds(20, 178, 33, 16);
		add(lblOxen);
		
		//weight label
		JLabel lblNewLabel = new JLabel("Weight");
		lblNewLabel.setBounds(448, 162, 43, 16);
		add(lblNewLabel);
		
		//price label
		JLabel lblfor = new JLabel("$40 (for 2)");
		lblfor.setBounds(74, 180, 66, 16);
		add(lblfor);
		
		//quantity label
		JLabel lblnone = new JLabel("----");
		lblnone.setBounds(148, 180, 39, 16);
		add(lblnone);
		
		//quantity label
		storeOxenAmount = new JLabel("" + storeInventory.get(0).getQuantity());
		storeOxenAmount.setBounds(215, 180, 33, 16);
		add(storeOxenAmount);
		
		//food label
		JLabel lblFood = new JLabel("Food");
		lblFood.setBounds(20, 201, 31, 16);
		add(lblFood);
		
		//price label
		JLabel lblfor_1 = new JLabel("$1");
		lblfor_1.setBounds(87, 201, 16, 16);
		add(lblfor_1);
		
		//weight label
		JLabel lblLbs = new JLabel("5 lbs");
		lblLbs.setBounds(137, 201, 31, 16);
		add(lblLbs);
		
		//quantity label
		storeFoodAmount = new JLabel("" + storeInventory.get(1).getQuantity());
		storeFoodAmount.setBounds(215, 201, 33, 16);
		add(storeFoodAmount);
	
		//clothing label
		JLabel lblClothing = new JLabel("Clothing");
		lblClothing.setBounds(20, 229, 54, 16);
		add(lblClothing);
		
		//price label
		JLabel label2 = new JLabel("$10");
		label2.setBounds(86, 229, 54, 16);
		add(label2);
		
		
		JLabel lblLbs_1 = new JLabel("2 lbs");
		lblLbs_1.setBounds(138, 229, 31, 16);
		add(lblLbs_1);
		
		storeClothingAmount = new JLabel("" + storeInventory.get(2).getQuantity());
		storeClothingAmount.setBounds(214, 229, 34, 16);
		add(storeClothingAmount);
		
		JLabel lblAmmunition = new JLabel("Ammo");
		lblAmmunition.setBounds(20, 257, 41, 16);
		add(lblAmmunition);
		
		JLabel lblRounds = new JLabel("$2 (for 20)");
		lblRounds.setBounds(74, 257, 66, 16);
		add(lblRounds);
		
		JLabel lblLbs_5 = new JLabel("3 lbs");
		lblLbs_5.setBounds(138, 257, 31, 16);
		add(lblLbs_5);
		
		storeAmmoAmount = new JLabel("" + storeInventory.get(3).getQuantity());
		storeAmmoAmount.setBounds(214, 257, 34, 16);
		add(storeAmmoAmount);
		
		JLabel lblWheel = new JLabel("Wheel");
		lblWheel.setBounds(20, 285, 37, 16);
		add(lblWheel);
		
		JLabel label_1 = new JLabel("$10");
		label_1.setBounds(87, 285, 24, 16);
		add(label_1);
		
		JLabel lblLbs_2 = new JLabel("75 lbs");
		lblLbs_2.setBounds(137, 285, 39, 16);
		add(lblLbs_2);
		
		storeWheelAmount = new JLabel("" + storeInventory.get(4).getQuantity());
		storeWheelAmount.setBounds(215, 285, 28, 16);
		add(storeWheelAmount);
		
		JLabel lblAxle = new JLabel("Axle");
		lblAxle.setBounds(20, 313, 28, 16);
		add(lblAxle);
		
		JLabel label_2 = new JLabel("$10");
		label_2.setBounds(87, 313, 24, 16);
		add(label_2);
		
		JLabel lblLbs_3 = new JLabel("125 lbs");
		lblLbs_3.setBounds(138, 313, 47, 16);
		add(lblLbs_3);
		
		storeAxleAmount = new JLabel("" + storeInventory.get(5).getQuantity());
		storeAxleAmount.setBounds(214, 313, 34, 16);
		add(storeAxleAmount);
		
		JLabel lblTongue = new JLabel("Tongue");
		lblTongue.setBounds(20, 341, 47, 16);
		add(lblTongue);
		
		JLabel label_3 = new JLabel("$10");
		label_3.setBounds(87, 341, 24, 16);
		add(label_3);
		
		JLabel lblLbs_4 = new JLabel("100 lbs");
		lblLbs_4.setBounds(138, 341, 47, 16);
		add(lblLbs_4);
		
		storeTongueAmount = new JLabel("" + storeInventory.get(6).getQuantity());
		storeTongueAmount.setBounds(214, 341, 24, 16);
		add(storeTongueAmount);
		
		btnBuy = new JButton("Buy");
		btnBuy.setBounds(258, 392, 75, 23);
		add(btnBuy);
		
		btnBuy.addActionListener(listener);
		
		
		JLabel wagonPriceOxen = new JLabel("$40(for 2)");
		wagonPriceOxen.setBounds(366, 174, 65, 14);
		add(wagonPriceOxen);
		
		JLabel label_11 = new JLabel("----");
		label_11.setBounds(452, 174, 39, 16);
		add(label_11);
		
		JLabel wagonOxenAmount = new JLabel("0");
		wagonOxenAmount.setBounds(522, 173, 33, 16);
		add(wagonOxenAmount);
		
		JLabel label_13 = new JLabel("$10");
		label_13.setBounds(388, 343, 24, 16);
		add(label_13);
		
		JLabel label_14 = new JLabel("100 lbs");
		label_14.setBounds(448, 341, 47, 16);
		add(label_14);
		
		JLabel wagonTongueAmount = new JLabel("0");
		wagonTongueAmount.setBounds(522, 341, 24, 16);
		add(wagonTongueAmount);
		
		JLabel wagonAxleAmount = new JLabel("0");
		wagonAxleAmount.setBounds(522, 313, 34, 16);
		add(wagonAxleAmount);
		
		JLabel label_17 = new JLabel("125 lbs");
		label_17.setBounds(448, 313, 47, 16);
		add(label_17);
		
		JLabel label_18 = new JLabel("$10");
		label_18.setBounds(388, 315, 24, 16);
		add(label_18);
		
		JLabel label_19 = new JLabel("$10");
		label_19.setBounds(388, 287, 24, 16);
		add(label_19);
		
		JLabel label_20 = new JLabel("75 lbs");
		label_20.setBounds(448, 285, 39, 16);
		add(label_20);
		
		JLabel wagonWheelAmount = new JLabel("0");
		wagonWheelAmount.setBounds(522, 287, 28, 16);
		add(wagonWheelAmount);
		
		JLabel wagonAmmoAmount = new JLabel("0");
		wagonAmmoAmount.setBounds(521, 257, 34, 16);
		add(wagonAmmoAmount);
		
		JLabel label_23 = new JLabel("3 lbs");
		label_23.setBounds(448, 257, 31, 16);
		add(label_23);
		
		JLabel label_24 = new JLabel("$2 (for 20)");
		label_24.setBounds(375, 259, 66, 16);
		add(label_24);
		
		JLabel label_25 = new JLabel("$10");
		label_25.setBounds(387, 231, 54, 16);
		add(label_25);
		
		JLabel label_26 = new JLabel("2 lbs");
		label_26.setBounds(448, 229, 31, 16);
		add(label_26);
		
		JLabel wagonClothingAmount = new JLabel("0");
		wagonClothingAmount.setBounds(521, 229, 34, 16);
		add(wagonClothingAmount);
		
		JLabel wagonFoodAmount = new JLabel("0");
		wagonFoodAmount.setBounds(522, 201, 33, 16);
		add(wagonFoodAmount);
		
		JLabel label_29 = new JLabel("5 lbs");
		label_29.setBounds(448, 201, 31, 16);
		add(label_29);
		
		JLabel label_30 = new JLabel("$1");
		label_30.setBounds(388, 203, 16, 16);
		add(label_30);
		
		btnSell = new JButton("Sell");
		btnSell.setBounds(258, 428, 75, 23);
		add(btnSell);
		
		btnSell.addActionListener(listener);
		
		btnReturn = new JButton("To trail");
		btnReturn.setBounds(258, 460, 75, 23);
		add(btnReturn);
		
		JLabel lblCostDisplay = new JLabel("Total Cost : ");
		lblCostDisplay.setBounds(38, 401, 73, 14);
		add(lblCostDisplay);
		
		JLabel lblMoneyDisplay = new JLabel("Money Left:");
		lblMoneyDisplay.setBounds(38, 421, 65, 14);
		add(lblMoneyDisplay);
		
		JLabel lblwagonWeightAddedDisplay = new JLabel("Weight Added");
		lblwagonWeightAddedDisplay.setBounds(366, 396, 82, 14);
		add(lblwagonWeightAddedDisplay);
		
		JLabel lblwagonWeightDisplay = new JLabel("Wagon Weight");
		lblwagonWeightDisplay.setBounds(366, 421, 101, 14);
		add(lblwagonWeightDisplay);
		
		lblCurrentCost = new JLabel("0");
		lblCurrentCost.setHorizontalAlignment(SwingConstants.CENTER);
		lblCurrentCost.setBounds(113, 401, 46, 14);
		add(lblCurrentCost);
		
		lblMoneyLeft = new JLabel("0");
		lblMoneyLeft.setHorizontalAlignment(SwingConstants.CENTER);
		lblMoneyLeft.setBounds(113, 421, 46, 14);
		add(lblMoneyLeft);
		lblMoneyLeft.setText("" + wagonInventory.getMoney());
		
		lblWeightAdded = new JLabel("0");
		lblWeightAdded.setHorizontalAlignment(SwingConstants.CENTER);
		lblWeightAdded.setBounds(448, 396, 46, 14);
		add(lblWeightAdded);
		
		lblWagonWeight = new JLabel("0");
		lblWagonWeight.setHorizontalAlignment(SwingConstants.CENTER);
		lblWagonWeight.setBounds(448, 421, 46, 14);
		add(lblWagonWeight);

		
		// GUI code ends here
		
		
		// Item list holds a new Item which will help us buy/sell items
		itemList = new ArrayList<Item>();
		itemList.add(new Item("Oxen",0,0, 40));
		itemList.add(new Item("Food",0,0, 1));
		itemList.add(new Item("Clothing",0,0, 10));
		itemList.add(new Item("Ammunition Box x20",0,0, 2));
		itemList.add(new Item("Wheels",0,0, 10));
		itemList.add(new Item("Axle",0,0, 10));
		itemList.add(new Item("Tongue",0,0, 10));
		

		// quantityArray will hold all the text fields
		quantityArray = new JTextField[7];
		quantityArray[0]= txtOxen;
		quantityArray[1]= txtFood;
		quantityArray[2]= txtClothing;
		quantityArray[3]= txtAmmo;
		quantityArray[4]= txtWheel;
		quantityArray[5]= txtAxle;
		quantityArray[6]= txtTongue;
		// End quantity array
		
		//Adding actionListener to all the textfields
		TextListener textListen = new TextListener();
		for(JTextField temp:quantityArray){
			temp.getDocument().addDocumentListener(textListen);
		}
		// Finished adding actionListener
		
		//storeLabelsArray will hold all the quantity labels for store
		storeLabelsArray = new JLabel[7];
		storeLabelsArray[0] = storeOxenAmount;
		storeLabelsArray[1] = storeFoodAmount;
		storeLabelsArray[2] = storeClothingAmount;
		storeLabelsArray[3] = storeAmmoAmount;
		storeLabelsArray[4] = storeWheelAmount;
		storeLabelsArray[5] = storeAxleAmount;
		storeLabelsArray[6] = storeTongueAmount;
		
		//wagonLabelsArray will hold all the quantity labels for wagon
		wagonLabelsArray = new JLabel[7];
		wagonLabelsArray[0] = wagonOxenAmount;
		wagonLabelsArray[1] = wagonFoodAmount;
		wagonLabelsArray[2] = wagonClothingAmount;
		wagonLabelsArray[3] = wagonAmmoAmount;
		wagonLabelsArray[4] = wagonWheelAmount;
		wagonLabelsArray[5] = wagonAxleAmount;
		wagonLabelsArray[6] = wagonTongueAmount;
	}
	
    public void paintComponent(Graphics g)
    {
    	super.paintComponent(g);
    	g.drawImage(newImg, 0, 0, 601, 494, this);
    }
    
    public void quantityChanged(){
    	final String blankString="";
		total = 0;
		totalWeight = 0;
		int index = -1;
		for (JTextField change: quantityArray){
			index++;
			try{
				if(!change.getText().equals("")){

					int temp = Integer.parseInt(change.getText());
					int tempW = Integer.parseInt(change.getText());
					temp = temp * wagonInventory.get(index).getPRICE();
					total = total + temp;
					tempW = tempW * wagonInventory.get(index).getWEIGHT_INDIVIDUAL();
					totalWeight = totalWeight+ tempW ;
					lblCurrentCost.setText("" + total);
					lblWeightAdded.setText("" + totalWeight);

				}
			}
			catch(Exception e){
				JOptionPane.showMessageDialog(null,"Invalid character Entered.","Enter valid character", JOptionPane.WARNING_MESSAGE);
				
				
				setTextFieldText("", change);
//				change.repaint();
			}
    	
    }
    }
    
   private void setTextFieldText(final String newString, final JTextField field){
		SwingUtilities.invokeLater(new Runnable(){
			public void run(){
				field.setText(newString);
			}
		});
	}
    
	public void buyItems(){
		for(int i =0; i <7;i++){
			if (!quantityArray[i].getText().equals("") && !quantityArray[i].getText().equals("0")  ){
				Item toBuy = itemList.get(i);
				storeController.buyItem(toBuy, Integer.parseInt(quantityArray[i].getText()));
				updateLabels();	
			}
		}
	}
	
	public void sellItems(){

		for(int i =0; i <7;i++){
			if (!quantityArray[i].getText().equals("")&& !quantityArray[i].getText().equals("0")){
				Item toSell = itemList.get(i);
				storeController.sellItem(toSell, Integer.parseInt(quantityArray[i].getText()));
				updateLabels();	
			}
		}
	}
	
	public void updateLabels(){
		
			for(int i = 0; i<7;i++){
				storeLabelsArray[i].setText(""+ (storeInventory.get(i).getQuantity()));
				wagonLabelsArray[i].setText("" + (wagonInventory.get(i).getQuantity()));
			//	System.out.println(wagonInventory.get(i).getQuantity());
		}
	}
	// This method returns the total weight of all the things requested to buy or sell
//	public int updateWeight(){
//		int totalWeight = 0;
//
//		for(int i = 0;i < 7;i++){
//			int quantityAsked = Integer.parseInt(quantityArray[i].getText());
//			if(quantityAsked > 0){
//				total = total + (quantityAsked * wagonInventory.get(i).getWEIGHT_INDIVIDUAL());
//
//			}
//		}
//		return totalWeight;
//	}
	
	
//	public  int calculateWeight(){
//		int totalWeight = 0;
//		for(Item temp: items){
//			totalWeight = totalWeight + temp.getTotalWeight();
//		}
//		return totalWeight;
//	}
	
	public JButton getButton(){
		return btnReturn;
	}

	private class TextListener implements DocumentListener{

		public void insertUpdate(DocumentEvent e) {
			quantityChanged();
		}

		public void removeUpdate(DocumentEvent e) {
			quantityChanged();
		}

		public void changedUpdate(DocumentEvent e) {
			quantityChanged();
		}
			
	}
	
	private class ButtonListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
		//	System.out.println("action performed");
			boolean quantitiesCorrect = true;
			boolean sellQuantitiesCorrect = true;
			int temp = 0;
			
			for(JTextField info : quantityArray){

				if(info.getText().equals(""))
					info.setText("0");
				if(Integer.parseInt(info.getText()) > Integer.parseInt(storeLabelsArray[temp].getText())){
					quantitiesCorrect = false;
				}
				if(Integer.parseInt(info.getText()) > Integer.parseInt(wagonLabelsArray[temp].getText())){
					sellQuantitiesCorrect = false;
				}
				
				temp++;	
			}
			if(e.getSource()== btnBuy){	//buy clicked
			//	System.out.println("buy clicked");
				if (quantitiesCorrect) {
					if(Integer.parseInt(lblCurrentCost.getText())> wagonInventory.getMoney())//checking money
						JOptionPane.showMessageDialog(null,"Not enough money, take out some items.","Weight Error", JOptionPane.WARNING_MESSAGE);
					
					else{	//check weight
						//System.out.println(calculateWeight() + "   " + wagonInv.getCurWeight()); // not working
						if (Integer.parseInt(lblWeightAdded.getText()) + wagonInventory.getCurWeight()> wagonInventory.getCapacity()) //if they are buying more than we can hold
							JOptionPane.showMessageDialog(null,"Wagon weight exceeded, take out some items.","Weight Error", JOptionPane.WARNING_MESSAGE);
						else{
							buyItems();
							wagonInventory.setMoney(wagonInventory.getMoney()- total);
							lblMoneyLeft.setText("" + wagonInventory.getMoney());
							int weightOfBoughtItems = Integer.parseInt(lblWeightAdded.getText());
							System.out.println("Current wagon weight is " + wagonInventory.getCurWeight() + " capacity is " + wagonInventory.getCapacity());
							lblWagonWeight.setText("" + (Integer.parseInt(lblWagonWeight.getText()) + weightOfBoughtItems));

						}
					}
				}
				else	//Request too many items from store
					JOptionPane.showMessageDialog(null,"Store does not have enough items that you are trying to buy.","Quantity Error", JOptionPane.WARNING_MESSAGE);
			}
			
			if(e.getSource()==btnSell){ //sell button clicked
				if(sellQuantitiesCorrect){
					sellItems();
					wagonInventory.setMoney(wagonInventory.getMoney()+ total);
					lblMoneyLeft.setText("" + wagonInventory.getMoney());
					int newWeight = Integer.parseInt(lblWeightAdded.getText());
					lblWagonWeight.setText("" + (wagonInventory.getCurWeight()));
				}
					else
					JOptionPane.showMessageDialog(null,"You do not have enough items to sell.","Quantity Error", JOptionPane.WARNING_MESSAGE);
					
			}
			
		}
	}
	
	
}
